﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace T01
{/// <summary>
/// User的数据访问类：增，删，改，查等操作
/// </summary>
    class UserDao
    {
        //MySQL的连接串描述
        private static string connStr = "server=localhost;user=root;password=123456;database=test";
        // private static string connStr = "server=localhost;uid=root;pwd=;database=test";
        /// <summary>
        /// 登录检查
        /// </summary>
        /// <param name="username">用户名 </param>
        /// <param name="password">密码</param>
        /// 
        /// <returns>0：无效 1：登录成功</returns>

        public static int LoginCheck(string username, string password)
        {
            //默认为无效的用户名和密码
            int number = 0;
            //1、构建Mysql连接对象
            MySqlConnection conn = new MySqlConnection(connStr);
            

            try
            {
                //2、打开数据库连接
                conn.Open();
                //比较用户名与密码的SQL语句
                string sql = "SELECT COUNT(id) FROM `tb_users` WHERE `username`='" + username + "'AND `password`='" + password + "'";

                Debug.WriteLine("SQL语句：" + sql);

                //3、创建SQL命令
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                //4、执行SQL命令
                object result = cmd.ExecuteScalar();
                if (result != null)
                {
                    number = Convert.ToInt32(result);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("数据库访问异常……");
                Debug.WriteLine("=============");
                Debug.WriteLine(ex.ToString());
                Debug.WriteLine("=============");
            }
            finally
            {
                if (conn != null)
                {
                    //5、关闭数据库连接
                    conn.Close();
                }
            }



            return number;
        }
        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <returns>用户集合</returns>
        public static List<User> LoadData()
        {
            //构建用户集合
            List<User> userList = new List<User>();

            MySqlConnection conn = new MySqlConnection(connStr);
            try
            {
                conn.Open();
                string sql = "SELECT FROM tb_users";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                //3、获取数据访问游标
                MySqlDataReader rdr = cmd.ExecuteReader();
                //4、依次访问数据记录并加入数据集合
                while (rdr.Read())
                {
                    User user = new User();
                    user.Id = Convert.ToInt64(rdr["id"]);
                    user.Username = Convert.ToString(rdr["username"]);
                    user.Password = Convert.ToString(rdr["password"]);
                    user.Nickname = Convert.ToString(rdr["nickname"]);
                    user.IsAdmin = Convert.ToInt16(rdr["is_admin"]) == 1 ? true : false;
                    userList.Add(user);

                }

                //5、关闭游标
                rdr.Close();

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());

            }
            finally
            {
                if (conn != null)
                    conn.Close();
            }
            return userList;
        }
        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="user">用户数据实体</param>
        /// <returns>MySQL自增ID</returns>
        public static long Insert(User user)
        {
            long insertId = 0;

            MySqlConnection conn = new MySqlConnection(connStr);
            try
            {
                conn.Open();
                string sql = "INSERT INTO tb_users "
                    + "(username.password,nickname,is_admin)"
                    + "VALUES"
                + "(@username,@password,@nickname,@is_admin)";
                MySqlCommand cmd = new MySqlCommand(sql, conn);
                //参数绑定
                cmd.Parameters.AddWithValue("@username", user.Username);
                cmd.Parameters.AddWithValue("@password", user.Password);
                cmd.Parameters.AddWithValue("@nickname", user.Nickname);
                cmd.Parameters.AddWithValue("@is_admin", user.IsAdmin);
                cmd.ExecuteNonQuery();
                insertId = cmd.LastInsertedId;
            } catch (Exception ex)
            {
                Debug.WriteLine("数据更新异常") + ex.ToString()); }

        }
        finally
        {

         return 0;
            }
               
        }
        public static void Update(User user)
        {
        MySqlConnection conn = new MySqlConnection(connStr);
        try
        {
            conn.Open();
            string sql = "UPDATE tb_users SET"
                          + "username=@username, "
                          + "password=@password, "
                          + "nickname=@nickname, "
                          + "is_admin=@is_admin "
                          + "WHERE id=@id ";
            MySqlCommand cmd = new MySqlCommand(sql, conn);
            //参数绑定
            cmd.Parameters.AddWithValue("@username", user.Username);
            cmd.Parameters.AddWithValue("@password", user.Password);
            cmd.Parameters.AddWithValue("@nickname", user.Nickname);
            cmd.Parameters.AddWithValue("@is_admin", user.IsAdmin);
            cmd.Parameters.AddWithValue("@id", user.Id);
            cmd.ExecuteNonQuery();
        
        }

    }
    public static void Delete(long id)
    {
        MySqlConnection conn = new MySqlConnection(connStr);
        try
        {
            conn.Open();
            string sql = "DELETE FROM tb_users WHERE id=@id";
            MySqlCommand cmd = new MySqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("@id", id);
            cmd.ExecuteNonQuery(){

            }

        }catch(Exception ex)
        {
            Debug.WriteLine("数据删除错误" + ex.ToString());
        }
        finally
        {
            if (conn != null)
            {
                conn.Close();
            }
        }
    }
}